package org.uned.agonzalo16.bitacora.web.tag;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.uned.agonzalo16.bitacora.dao.BlogContributionDao;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.BlogContribution;
import org.uned.agonzalo16.bitacora.domain.User;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;
import org.uned.agonzalo16.bitacora.service.security.AuthenticationProvider;

@Configurable
@SuppressWarnings("serial")
public class UserBlogsTag extends TagSupport {

	private String var;

	@Autowired
	private transient UserDao userDao;

	@Autowired
	private transient AuthenticationProvider authenticationProvider;

	@Autowired
	private transient BlogContributionDao blogContributionDao;

	public void setVar(String var) {
		this.var = var;
	}

	@Override
	public int doStartTag() throws JspException {

		AuthenticatedUser principal = authenticationProvider.getCurrentUserDetails();
		User user = userDao.get(principal.getId());

		List<BlogContribution> blogs = blogContributionDao.findByUser(user);
		Collections.sort(blogs, new Comparator<BlogContribution>() {
			@Override
			public int compare(BlogContribution b1, BlogContribution b2) {
				return b1.getBlog().getName().compareToIgnoreCase(b2.getBlog().getName());
			}
		});

		pageContext.setAttribute(var, blogs);
		return SKIP_BODY;
	}
}
